﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Sheego.Service.X400.Job.Shared;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Job.Impl
{
    class ConsoleProcess : IConsoleProcess
    {
        #region IConsoleProcess Members

        public int Call(string Command, string Arguments, string WorkingDirectory, IList<string> output, IList<string> error)
        {

            if (String.IsNullOrWhiteSpace(Command))
                throw new ArgumentNullException("Command");

            if (String.IsNullOrWhiteSpace(Arguments))
                throw new ArgumentNullException("Arguments");

            if(output == null)
                throw new ArgumentNullException("output");

            if (error == null)
                throw new ArgumentNullException("error");

            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.FileName = Command;
            startInfo.Arguments = " " + Arguments;


            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.CreateNoWindow = true;

            if(WorkingDirectory != null)
                startInfo.WorkingDirectory = WorkingDirectory;


            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                // You can pass any delegate that matches the appropriate 
                // signature to ErrorDataReceived and OutputDataReceived
                exeProcess.ErrorDataReceived += (sender, errorLine) => { if (errorLine.Data != null) error.Add(errorLine.Data); };
                exeProcess.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null) output.Add(outputLine.Data); };

                exeProcess.BeginErrorReadLine();
                exeProcess.BeginOutputReadLine();

                exeProcess.WaitForExit();

                return exeProcess.ExitCode;
            }


        }

        #endregion
    }
}
